package com.example.griddemo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.griddemo.R;
import com.example.griddemo.viewmodel.NewGoodsList;

import java.util.ArrayList;
import java.util.List;

public class NewGoodsAdapter extends RecyclerView.Adapter<NewGoodsAdapter.ViewHolder> {
    private final Context context;
    private List<NewGoodsList> dataList;

    public NewGoodsAdapter(Context context, List<NewGoodsList> dataList) {
        this.context = context.getApplicationContext();
        this.dataList = dataList != null ? dataList : new ArrayList<>();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.home_newsgoods_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        NewGoodsList item = dataList.get(position);

        try {
            Glide.with(context)
                    .load(item.getPicUrl())
                    .into(holder.ivImage);

            holder.tvName.setText(item.getName());

            try {
                double price = Double.parseDouble(item.getRetailPrice());
                holder.tvPrice.setText(String.format("¥%.2f", price));
            } catch (NumberFormatException e) {
                holder.tvPrice.setText("¥0.00");
            }
        } catch (Exception e) {
            holder.tvName.setText("数据加载失败");
        }
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public void updateData(List<NewGoodsList> newData) {
        this.dataList = newData != null ? newData : new ArrayList<>();
        notifyDataSetChanged();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivImage;
        TextView tvName;
        TextView tvPrice;

        ViewHolder(View itemView) {
            super(itemView);
            ivImage = itemView.findViewById(R.id.iv_newGoods_pivUrl);
            tvName = itemView.findViewById(R.id.tv_newGoods_name);
            tvPrice = itemView.findViewById(R.id.tv_newGoods_retailPrice);
        }
    }
}